package edu.pku.sei.autounit.generator;

import java.util.Map;

import edu.pku.sei.autounit.core.Variable;
import edu.pku.sei.autounit.reflect.Array;
import edu.pku.sei.autounit.reflect.Primitive;
import edu.pku.sei.autounit.reflect.Type;
import edu.pku.sei.autounit.util.Statements;

public class ArrayVariable implements Variable{

	private Array type;
	private Variable [] elements ;
	private String name;
	public ArrayVariable(Array type,String name,Variable [] elements){
		this.type = type;
		this.elements = elements;
		this.name = name;
	}
	
	public Statements getInitCode(Map<String, String> map) {
		Statements s = new Statements();
		for(Variable v:elements)
			s.merge(v.getInitCode(map));
		if(type.getElementType() instanceof Primitive){
			StringBuffer sb = new StringBuffer();
			sb.append(type.getName(map));
			sb.append(" "+name+" = {");
			for(Variable v:elements)
				sb.append(v.getValue()+",");
			String temp = sb.toString();
			if(temp.endsWith(","))
				temp = temp.substring(0,temp.length()-1)+"};";
			else
				temp = temp+"}:";
			s.insertStatement(temp);
			return s;
		}
		
		else{
			StringBuffer sb = new StringBuffer();
			String typeName = type.getName(map);
			sb.append(typeName);
			sb.append(" "+name+" = new ");
			int index = typeName.indexOf("[");
			String left = typeName.substring(0,index);
			if(left.indexOf('<')!=-1)
			left = left.substring(0,left.indexOf('<'));
			String right = typeName.substring(index+1,typeName.length());
			typeName = left+"["+elements.length+right;
			sb.append(typeName);
			sb.append(";");
			s.insertStatement(sb.toString());
			
			for(int i = 0;i<elements.length;i++)
				s.insertStatement(name+"["+i+"] = "+elements[i].getValue()+";");
			return s;
			
		}
		
	}

	public Type getType() {
		return type;
	}

	public String getValue() {
		return name;
	}

}
